package com.book.activeMQ.consumers;

import com.book.pojo.OrderDetail;
import com.book.pojo.TempOrder;
import com.book.service.OrderService;
import com.book.service.TempOrderService;
import com.book.service.domain.OrderCreateTempMqService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.List;

/**
 * @Author 李锦程
 * @Date 2021/4/27 1:47 下午
 * @Package com.book.activeMQ.consumers
 * @Version 1.0
 */
@Slf4j
@Component
public class SaveOrderDetail implements MessageListener {
    @Autowired
    private OrderService orderService;
    @Autowired
    private TempOrderService tempOrderService;
    @Autowired
    private OrderCreateTempMqService orderCreateTempMqService;
    @Override
    public void onMessage(Message message) {
        try {

            String orderNo = ((TextMessage) message).getText();
            log.info("SaveOrderDetail#orderNo:{}", orderNo);
            List<TempOrder> tempOrder = tempOrderService.getTempOrder(orderNo);
            if (CollectionUtils.isEmpty(tempOrder)) {
                return;
            }
            log.info("SaveOrderDetail#tempOrder:{}", tempOrder);
            List<OrderDetail> orderDetailList = Lists.newArrayList();
            tempOrder.forEach(m -> {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setOrderCode(orderNo);
                orderDetail.setUbCode(m.getBookCode());
                orderDetail.setOrNum(m.getNum().shortValue());
                orderDetail.setOrPrice(m.getTotalPrice());
                orderDetailList.add(orderDetail);
            });
            log.info("SaveOrderDetail orderDetailList:{}", orderDetailList);
            orderService.saveOrderDetail(orderDetailList);
            orderCreateTempMqService.refreshBook(tempOrder);
        }catch (Exception e){
            log.error("SaveOrderDetail error",e);
        }
    }
}
